package client

import (
	study "0411zk/common/proto"
	"context"
	"google.golang.org/grpc"
)

type Handler func(ctx context.Context, in study.StudyClient) (interface{}, error)

func StudyClient(ctx context.Context, handler Handler) (interface{}, error) {
	dial, err := grpc.Dial("127.0.0.1:8888", grpc.WithInsecure())
	if err != nil {
		return nil, err
	}
	client := study.NewStudyClient(dial)

	res, err := handler(ctx, client)
	if err != nil {
		return nil, err
	}

	defer dial.Close()
	return res, nil
}

func UserRegister(ctx context.Context, i *study.UserRegisterReq) (*study.UserRegisterResp, error) {
	client, err := StudyClient(ctx, func(ctx context.Context, in study.StudyClient) (interface{}, error) {
		register, err := in.UserRegister(ctx, i)
		if err != nil {
			return nil, err
		}
		return register, nil
	})
	if err != nil {
		return nil, err
	}
	return client.(*study.UserRegisterResp), nil
}

func BrowseCourses(ctx context.Context, i *study.BrowseCoursesReq) (*study.BrowseCoursesResp, error) {
	client, err := StudyClient(ctx, func(ctx context.Context, in study.StudyClient) (interface{}, error) {
		register, err := in.BrowseCourses(ctx, i)
		if err != nil {
			return nil, err
		}
		return register, nil
	})
	if err != nil {
		return nil, err
	}
	return client.(*study.BrowseCoursesResp), nil
}

func BrowseCoursesAdd(ctx context.Context, i *study.BrowseCoursesAddReq) (*study.BrowseCoursesAddResp, error) {
	client, err := StudyClient(ctx, func(ctx context.Context, in study.StudyClient) (interface{}, error) {
		register, err := in.BrowseCoursesAdd(ctx, i)
		if err != nil {
			return nil, err
		}
		return register, nil
	})
	if err != nil {
		return nil, err
	}
	return client.(*study.BrowseCoursesAddResp), nil
}

func BrowseCoursesDel(ctx context.Context, i *study.BrowseCoursesDelReq) (*study.BrowseCoursesDelResp, error) {
	client, err := StudyClient(ctx, func(ctx context.Context, in study.StudyClient) (interface{}, error) {
		register, err := in.BrowseCoursesDel(ctx, i)
		if err != nil {
			return nil, err
		}
		return register, nil
	})
	if err != nil {
		return nil, err
	}
	return client.(*study.BrowseCoursesDelResp), nil
}

func CoursesOrder(ctx context.Context, i *study.CoursesOrderReq) (*study.CoursesOrderResp, error) {
	client, err := StudyClient(ctx, func(ctx context.Context, in study.StudyClient) (interface{}, error) {
		register, err := in.CoursesOrder(ctx, i)
		if err != nil {
			return nil, err
		}
		return register, nil
	})
	if err != nil {
		return nil, err
	}
	return client.(*study.CoursesOrderResp), nil
}
